//
//  DataController+Cache.m
//  WKCarInsurance
//
//  Created by 姚永波 on 2017/6/14.
//  Copyright © 2017年 wkbins. All rights reserved.
//

// Cache数据
#import "CacheItem.h"
#import "DataController+Cache.h"



#define kDataControllerCacheMaxCount		1000
#define kCacheDataFile								@"CacheData.dat"

@implementation DataController (Cache)

- (void)initCacheData
{
    if (cacheData == nil) {
        cacheData = [[CacheData alloc] init];
    }
}

- (NSMutableArray *)arrayCachedData
{
    [self initCacheData];
    if ([cacheData arrayCacheData] == nil) {
        // 获取document文件夹位置
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *cacheDirectory = [paths objectAtIndex:0];
        
        // 写入文件
        NSString *cachePath = [cacheDirectory stringByAppendingPathComponent:kCacheDataFile];
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            NSData *data = [NSData dataWithContentsOfFile:cachePath];
            if (data) {
                NSMutableArray *arrayCacheDataFromFile = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                [self setArrayCacheData:arrayCacheDataFromFile];
            }else{
                NSMutableArray *arrayCacheDataDefault = [[NSMutableArray alloc] init];
                [self setArrayCacheData:arrayCacheDataDefault];
            }
        }else{
            NSMutableArray *arrayCachedDataDefault = [[NSMutableArray alloc] init];
            [self setArrayCacheData:arrayCachedDataDefault];
        }
    }
    return [cacheData arrayCacheData];
}

- (void)setArrayCacheData:(NSMutableArray *)arrayCacheDataNew
{
    [self initCacheData];
    [cacheData setArrayCacheData:arrayCacheDataNew];
}
- (void)addCache:(NSData *)data andCacheKey:(NSString *)cacheKey
{
    [self addCache:data andCacheKey:cacheKey andCachedNSURLResponse:[[NSURLResponse alloc] init]];
}
- (void)addCache:(NSData *)data andCacheKey:(NSString *)cacheKey andCachedNSURLResponse:(NSURLResponse *)response
{
    for (CacheItem *cacheItem in [self arrayCachedData]) {
        if ([[cacheItem cacheKey] isEqualToString:cacheKey]) {
            if ([data isKindOfClass:[NSData class]]) {
                [cacheItem setDataCache:data];
            }else if ([data isKindOfClass:[NSDictionary class]] ||[data isKindOfClass:[NSMutableDictionary class]]){
                NSData *encodedata =    [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
                [cacheItem setDataCache:encodedata];
            }else if ([data isKindOfClass:[NSString class]]|| [data isKindOfClass:[NSMutableString class]]){
                NSData* strData = [(NSString *)data dataUsingEncoding:NSUTF8StringEncoding];
                [cacheItem setDataCache:strData];
            }else{
                NSData* strData = [@"NoCachedata" dataUsingEncoding:NSUTF8StringEncoding];
                [cacheItem setDataCache:strData];
            }
            [cacheItem setCacheResponse:response];
            [self saveCachedData];
            return;
        }
    }
    // 缓存数据量已超过预计值，先删除最久未加载的缓存数据
    if ([[self arrayCachedData] count] >= kDataControllerCacheMaxCount) {
        [[self arrayCachedData] removeObjectAtIndex:0];
    }
    // 添加缓存数据
    CacheItem *cacheItem = [[CacheItem alloc] init];
    [cacheItem setCacheKey:cacheKey];
    [cacheItem setCacheResponse:response];
    [cacheItem setDataCache:data];
    
    [[self arrayCachedData] addObject:cacheItem];
    [self saveCachedData];
}

- (NSData *)loadCacheDataWithKey:(NSString *)cacheKey
{
    NSInteger cacheDataCount = [[self arrayCachedData] count];
    for (NSInteger i=0; i < cacheDataCount; i++) {
        CacheItem *cacheItem = [[self arrayCachedData] objectAtIndex:i];
        if ([[cacheItem cacheKey] isEqualToString:cacheKey]) {
            NSData *dataCache = [[cacheItem dataCache] copy];
            return dataCache;
        }
    }
    return nil;
}

- (NSURLResponse *)loadCacheResponseWithKey:(NSString *)cacheKey
{
    NSInteger cacheDataCount = [[self arrayCachedData] count];
    for (NSInteger i=0; i < cacheDataCount; i++) {
        CacheItem *cacheItem = [[self arrayCachedData] objectAtIndex:i];
        if ([[cacheItem cacheKey] isEqualToString:cacheKey]) {
            NSURLResponse *cacheResponse = [[cacheItem cacheResponse] copy];
            return cacheResponse;
        }
    }
    return nil;
}


- (BOOL)findCachedWithKey:(NSString *)cacheKey
{
    for (CacheItem *cacheItem in [self arrayCachedData]) {
        if ([[cacheItem cacheKey] isEqualToString:cacheKey]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)deleteCacheWithKey:(NSString *)cacheKey
{
    for (CacheItem *cacheItem in [self arrayCachedData]) {
        if ([[cacheItem cacheKey] isEqualToString:cacheKey])
        {
            [[self arrayCachedData] removeObject:cacheItem];
            return YES;
        }
    }
    return NO;
}


- (void)saveCachedData
{
    if ((cacheData != nil) && [cacheData arrayCacheData] != nil) {
        // document文件夹位置
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *cacheDirectory  = [paths objectAtIndex:0];
        
        NSData *dataTmp = [NSKeyedArchiver archivedDataWithRootObject:[cacheData arrayCacheData]];
        //写入文件
        NSString *cachePath = [cacheDirectory stringByAppendingPathComponent:kCacheDataFile];
        [dataTmp writeToFile:cachePath atomically:YES];
    }
}
@end
